import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';

import { type DeviceItem } from '@/api/deviceManagerApi';
import { equipmentProductListApi } from '@/api/equipmentProductApi';
import { getEnumLabel, ProductNodeType } from '@/constants';

import DeviceForm from './DeviceForm';

import type { FormInstance, UploadFile, UploadProps } from 'antd';

/**
 * 设备添加表单组件属性
 */
interface DeviceAddProps {
  /** 表单实例 */
  form: FormInstance;
  /** 设备数据 */
  data: DeviceItem;
  /** 模式：新增或编辑 */
  mode?: 'add' | 'edit';
  /** Tab切换回调 */
  onTabChange?: (activeTab: string) => void;
  /** 文件变化回调 */
  onFileChange?: (file: File | null) => void;
}

/**
 * 暴露给父组件的方法接口
 */
export interface DeviceAddFormRef {
  /** 获取当前激活的Tab */
  getActiveTab: () => string;
  /** 获取上传的文件 */
  getUploadFile: () => File | null;
}

/**
 * 设备添加/编辑表单组件
 * 支持单个添加和批量导入两种模式
 */
const DeviceAddForm = forwardRef<DeviceAddFormRef, DeviceAddProps>((props, ref) => {
  const { form, data: _data, mode = 'add', onTabChange, onFileChange } = props;

  // 文件引用
  const fileRef = useRef<File | null>(null);

  // 状态管理
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [activeTab, setActiveTab] = useState<string>('single'); // 当前激活的Tab

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    getActiveTab: () => activeTab,
    getUploadFile: () => fileRef.current,
  }));

  /**
   * 自定义上传请求处理
   * 不实际上传文件，只存储文件引用供后续批量导入使用
   */
  const customRequest: UploadProps['customRequest'] = ({ file, onSuccess }) => {
    try {
      // 验证文件类型
      const allowedTypes = [
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      ];

      if (!allowedTypes.includes((file as File).type)) {
        window.$message.error('只支持Excel文件格式(.xls, .xlsx)');
        return;
      }

      // 验证文件大小（限制10MB）
      const maxSize = 10 * 1024 * 1024;
      if ((file as File).size > maxSize) {
        window.$message.error('文件大小不能超过10MB');
        return;
      }

      // 将文件存储在 fileRef 中
      fileRef.current = file as File;

      // 模拟上传成功
      setTimeout(() => {
        onSuccess?.('ok');
      }, 100);

      // 通知父组件文件变化
      onFileChange?.(file as File);
    } catch (error) {
      console.error('文件处理失败:', error);
      window.$message.error('文件处理失败，请重试');
    }
  };

  /**
   * 获取产品列表
   */
  const fetchRemoteSelectData = async (params: FetchParams) => {
    const res = await equipmentProductListApi({
      ...params,
    });
    if (res.success) {
      const { page, pageSize } = params;
      const hasMore = page * pageSize < res.data.total;
      const newData = res.data.records.map(item => {
        return {
          ...item,
          label: `${item.productName}(${getEnumLabel(ProductNodeType, item.nodeType || 1)})`,
          value: item.code,
        };
      });
      return {
        data: newData,
        total: res.data.total,
        hasMore,
      };
    }
    return {
      data: [],
      total: 0,
      hasMore: false,
    };
  };

  // Tab切换处理
  const handleTabChange = (key: string) => {
    setActiveTab(key);
    onTabChange?.(key);
  };

  // 文件变化处理
  useEffect(() => {
    onFileChange?.(fileRef.current);
  }, [fileRef.current, onFileChange]);

  // 编辑模式：只显示单个设备表单
  if (mode === 'edit') {
    return (
      <div>
        <DeviceForm form={form} onMapSelect={() => {}} />
      </div>
    );
  }

  // 新增模式：显示Tab切换
  return (
    <div>
      <ATabs defaultActiveKey="single" className="mb-4" onChange={handleTabChange}>
        <ATabs.TabPane tab="单个添加" key="single">
          <DeviceForm form={form} onMapSelect={() => {}} />
        </ATabs.TabPane>

        <ATabs.TabPane tab="批量添加" key="batch">
          <div className="space-y-6">
            {/* 提示信息 */}
            <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
              <div className="text-blue-800 text-sm">
                你可
                <a
                  href="http://117.176.131.209:8011/IoT%E8%83%BD%E5%8A%9B%E5%B9%B3%E5%8F%B0%E8%AE%BE%E5%A4%87%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88.xlsx"
                  target="_blank"
                  className="cursor-pointer color-primary"
                >
                  下载空的模板表格
                </a>
                ，填写信息后上传
              </div>
            </div>

            {/* 文件上传区域 */}
            <div>
              <div className="text-sm text-gray-700 mb-3">上传设备表格文件：</div>
              <AUpload.Dragger
                name="file"
                multiple={false}
                accept=".xlsx,.xls,.csv"
                customRequest={customRequest}
                onChange={info => {
                  const { file, fileList: newFileList } = info;
                  if (file.status === 'removed') {
                    setFileList([]);
                    fileRef.current = null;
                  } else if (file.status === 'done' || file.status === 'uploading') {
                    // 确保只保留一个文件
                    setFileList(newFileList.slice(-1));
                  }
                }}
                fileList={fileList}
                className="bg-gray-50"
                showUploadList={{
                  showPreviewIcon: false,
                  showDownloadIcon: false,
                  showRemoveIcon: true,
                }}
                onRemove={() => {
                  // 手动移除文件时清空文件列表和文件引用
                  setFileList([]);
                  fileRef.current = null;
                  return true;
                }}
              >
                <div className="py-8">
                  <div className="text-center">
                    <AButton type="primary" ghost>
                      选择文件
                    </AButton>
                  </div>
                  <div className="text-center text-gray-500 text-sm mt-4">
                    请谨慎操作，提交以后，将不能批量修改
                  </div>
                </div>
              </AUpload.Dragger>
            </div>

            {/* 所属产品选择 */}
            <div>
              <AForm.Item
                name="productCode"
                label="所属产品"
                rules={[{ required: true, message: '请选择产品类型' }]}
              >
                <RemoteSelect
                  searchParams={{
                    time: Date.now(),
                  }}
                  onSelect={(_e, _options) => {
                    // form.setFieldValue('enterpriseName', options.label);
                  }}
                  fetchData={fetchRemoteSelectData}
                />
              </AForm.Item>
            </div>
          </div>
        </ATabs.TabPane>
      </ATabs>
    </div>
  );
});

DeviceAddForm.displayName = 'DeviceAddForm';

export default DeviceAddForm;
